﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace MediaLibraryManagement.Common
{
    public static class Utilities
    {
        public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
        {
            var ratioX = (double)maxWidth / image.Width;
            var ratioY = (double)maxHeight / image.Height;
            var ratio = Math.Min(ratioX, ratioY);

            var newWidth = (int)(image.Width * ratio);
            var newHeight = (int)(image.Height * ratio);

            var newImage = new Bitmap(newWidth, newHeight);
            Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
            return newImage;
        }

        public static byte[] ImageToByteArray(Image image)
        {
            byte[] data;
            BinaryFormatter bf = new BinaryFormatter();
            using (MemoryStream ms = new MemoryStream())
            {
                //image.Save(ms, image.RawFormat);
                bf.Serialize(ms, image);
                data = ms.ToArray();
            }
            return data;
        }

        public static Image ByteArrayToImage(byte[] byteArray)
        {
            Image image;
            using (MemoryStream ms = new MemoryStream(byteArray))
            {
                BinaryFormatter bf = new BinaryFormatter();
                ms.Write(byteArray, 0, byteArray.Length);
                ms.Seek(0, SeekOrigin.Begin);
                image = (Image)bf.Deserialize(ms);
                //image = Image.FromStream(ms);
            }
            return image;
        }
    }
}
